package com.apkicon.test;

import net.dongliu.apk.parser.ApkFile;
import net.dongliu.apk.parser.bean.ApkMeta;
import com.apkicon.parser.ApkResourceResolver;
import com.apkicon.parser.ResourcesArscParser;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.util.Map;

/**
 * Background Image Extractor - Extract background PNG from APK
 */
public class BackgroundExtractor {
    
    public static void main(String[] args) {
        String apkPath = "test.apk";
        
        try (ApkFile apkFile = new ApkFile(apkPath)) {
            System.out.println("Extracting background image from: " + apkPath);
            
            // 1. Parse APK basic info
            ApkMeta apkMeta = apkFile.getApkMeta();
            System.out.println("App Info:");
            System.out.println("  Package: " + apkMeta.getPackageName());
            System.out.println("  Version: " + apkMeta.getVersionName() + " (" + apkMeta.getVersionCode() + ")");
            System.out.println("  App Name: " + apkMeta.getLabel());
            
            // 2. Get icon path
            String iconPath = apkMeta.getIcon();
            System.out.println("Icon Path: " + iconPath);
            
            // 3. Parse Adaptive Icon resources
            System.out.println("Parsing Adaptive Icon resources: " + iconPath);
            ApkResourceResolver.AdaptiveIconResources resources = ApkResourceResolver.resolveAdaptiveIconResources(apkFile, iconPath);
            
            // 4. Extract background image
            String backgroundPath = resources.getBackgroundPath();
            System.out.println("Background Resource Path: " + backgroundPath);
            
            if (backgroundPath != null) {
                // 5. Read background image from APK
                byte[] backgroundData = apkFile.getFileData(backgroundPath);
                if (backgroundData != null) {
                    System.out.println("Found background file: " + backgroundPath + " (" + backgroundData.length + " bytes)");
                    
                    // 6. Save as PNG file
                    BufferedImage backgroundImage = ImageIO.read(new ByteArrayInputStream(backgroundData));
                    if (backgroundImage != null) {
                        System.out.println("Background image size: " + backgroundImage.getWidth() + "x" + backgroundImage.getHeight());
                        
                        // Save original background image
                        File outputFile = new File("background_original.png");
                        ImageIO.write(backgroundImage, "PNG", outputFile);
                        System.out.println("Background image saved: " + outputFile.getName());
                        
                        // If it's a 9-patch image, also save a processed version
                        if (backgroundPath.endsWith(".9.png")) {
                            System.out.println("Detected 9-patch image, creating processed version...");
                            BufferedImage processedImage = processNinePatchImage(backgroundImage);
                            File processedFile = new File("background_processed.png");
                            ImageIO.write(processedImage, "PNG", processedFile);
                            System.out.println("Processed background image saved: " + processedFile.getName());
                        }
                        
                    } else {
                        System.err.println("Failed to read background image data");
                    }
                } else {
                    System.err.println("Background file not found: " + backgroundPath);
                }
            } else {
                System.err.println("Background resource path not found");
            }
            
        } catch (Exception e) {
            System.err.println("Failed to extract background image: " + e.getMessage());
            e.printStackTrace();
        }
    }
    
    /**
     * Process 9-patch image, remove 9-patch markers
     */
    private static BufferedImage processNinePatchImage(BufferedImage ninePatchImage) {
        int width = ninePatchImage.getWidth();
        int height = ninePatchImage.getHeight();
        
        // Remove 1-pixel border of 9-patch
        BufferedImage processedImage = new BufferedImage(width - 2, height - 2, BufferedImage.TYPE_INT_ARGB);
        
        // Copy content area (skip border)
        for (int y = 1; y < height - 1; y++) {
            for (int x = 1; x < width - 1; x++) {
                int pixel = ninePatchImage.getRGB(x, y);
                processedImage.setRGB(x - 1, y - 1, pixel);
            }
        }
        
        return processedImage;
    }
}